package com.maxd.service.point;

import com.maxd.component.sequence.SeqTools;
import com.maxd.constants.PointScene;
import com.maxd.model.ActivityJoinRecord;
import com.maxd.model.Orders;
import com.maxd.model.PointRecord;
import com.maxd.model.UserInfo;
import com.maxd.respository.PointRecordRepository;
import com.maxd.respository.userinfo.UserJpaRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;

@Slf4j
@Service
public class PointServiceImpl implements IPointService {

    @Value("${classes.partner}")
    private String partnerTypeId;

    @Value("${classes.instructor}")
    private String instructorTypeId;

    @Value("${point.produce-rate}")
    private String produceRate;

    @Value("${point.proportion}")
    private String proportion;

    @Autowired
    private UserJpaRepository userJpaRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PointRecordRepository pointRecordRepository;


    @Override
    public void orderPointProduce(Orders order) {
        try {
            if(Long.valueOf(partnerTypeId).equals(order.getType())) {
                log.info("合伙人下单，不累计积分");
                return;
            }
            pointProduce(order.getUserId(), order.getPayMoney(), String.valueOf(order.getGoodsId()), order.getTitle(), order.getOrderNum());
        } catch (Exception e) {
            log.error("下单产生积分失败.", e);
        }
    }

    @Override
    public void activityPointProduce(ActivityJoinRecord record) {
        try {
            log.info("参与活动支付成功累计积分.");
            pointProduce(record.getUserId(), record.getAmount(), String.valueOf(record.getActivityId()), String.valueOf(record.getActivityName()), record.getTransId());
        } catch (Exception e) {
            log.error("参与活动支付成功累计积分失败.", e);
        }
    }

    private void pointProduce(Long userId, BigDecimal amount, String itemId, String itemName, String businessId) {
        UserInfo userInfo = userJpaRepository.findById(userId).orElse(null);
        log.info("获取到订单的用户信息为:{}", JsonUtils.toJsonString(userInfo));
        if(userInfo == null) {
            log.warn("用户信息为空，不累计积分，用户ID：{}", userInfo);
            return;
        }
        // 计算总的积分数
        BigDecimal totalPoint = amount.multiply(new BigDecimal(produceRate)).setScale(0, RoundingMode.DOWN);
        if(totalPoint.compareTo(BigDecimal.ONE) < 0) {
            log.info("计算的积分小于1，不累计");
            return;
        }
        BigDecimal parentPoint = BigDecimal.ZERO;
        // 有邀请人的情况
        if(StringUtils.isNotEmpty(userInfo.getInvitation())) {
            UserInfo parentUser = userRepository.getUserByRelationId(userInfo.getInvitation());
            if(parentUser == null) {
                log.info("上级用户获取不到，不分成给上级用户.");
            }
            parentPoint = totalPoint.multiply(new BigDecimal(proportion)).setScale(0, RoundingMode.DOWN);
            if(parentPoint.compareTo(BigDecimal.ONE) >= 0) {
                insertRecord(parentUser.getId(), PointScene.GEN_SUB_BUY, parentPoint, itemId, itemName, businessId, userInfo.getId(), userInfo.getPhone());
            }
        }
        BigDecimal selfPoint = totalPoint.subtract(parentPoint);
        if(selfPoint.compareTo(BigDecimal.ONE) >= 0) {
            insertRecord(userId, PointScene.GEN_BUY, selfPoint, itemId, itemName, businessId);
        }
    }


    private PointRecord insertRecord(Long userId, PointScene scene, BigDecimal point, String itemId, String itemName, String businessId) {
        return insertRecord(userId, scene, point, itemId, itemName, businessId, null, null);
    }

    private PointRecord insertRecord(Long userId, PointScene scene, BigDecimal point, String itemId, String itemName, String businessId, Long subUserId, String subUserPhone) {
        String seq = SeqTools.dateSeq();
        PointRecord record = new PointRecord();
        record.setSeqNo(seq);
        record.setRecordType("GEN");
        record.setPointAmount(point);
        record.setUserId(userId);
        record.setSceneCode(scene.getCode());
        record.setSubUserId(subUserId);
        record.setSubUserPhone(subUserPhone);

        record.setBusinessId(businessId);
        record.setItemId(itemId);
        record.setItemName(itemName);

        record.setCreateBy(String.valueOf(userId));
        record.setUpdateBy(String.valueOf(userId));

        pointRecordRepository.save(record);
        log.info("插入积分记录表记录: {}", JsonUtils.toJsonString(record));
        return record;
    }
}
